package com.ninth_group.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        return builder
                .modules(new JavaTimeModule(), httpMethodModule()) // 同时加载两个模块
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build();
    }

    @Bean
    public Module httpMethodModule() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(HttpMethod.class, new HttpMethodDeserializer());
        module.addSerializer(HttpMethod.class, new HttpMethodSerializer()); // 关键添加
        return module;
    }

    // 自定义反序列化器
    public static class HttpMethodDeserializer
            extends com.fasterxml.jackson.databind.deser.std.StdDeserializer<HttpMethod> {

        public HttpMethodDeserializer() {
            super(HttpMethod.class);
        }

        @Override
        public HttpMethod deserialize(
                com.fasterxml.jackson.core.JsonParser p,
                com.fasterxml.jackson.databind.DeserializationContext ctxt
        ) throws java.io.IOException {
            String value = p.getText().toUpperCase();
            return HttpMethod.valueOf(value);
        }
    }

    // 新增序列化器
    public static class HttpMethodSerializer
            extends StdSerializer<HttpMethod> {

        public HttpMethodSerializer() {
            super(HttpMethod.class);
        }

        @Override
        public void serialize(
                HttpMethod value,
                JsonGenerator gen,
                SerializerProvider provider
        ) throws IOException {
            gen.writeString(value.name()); // 将 HttpMethod 序列化为字符串（如 "GET"）
        }
    }
}
